define(['knockout', 'util','config','store', 'jqxcore', 'jqxdata', 'jqxbuttons', 'jqxscrollbar', 'jqxdatatable', 'jqxtreegrid'], function (ko, Util,Config,Store) {
    function ViewModel(params) {
        $.extend(this,{
            preOperation:function () {
                return true
            },
            _store:undefined
        });
        Util.extend(this, params);

        var scope = this;

        scope._id = 'treeGrid_{0}'.formatTpl(Util.uuid(8,16));
        scope._jqId = '#' + scope._id;
        scope._css = {'xgx-jqx-tree-grid':true};
        scope._selectedId = undefined;
        scope._operations = Util.generateOperations(scope.operations);
        scope._onOperation = function (operation, id) {
            var record = scope._store.getRecordById(id);

            if (scope.preOperation(operation) && record) {
                if (scope._store) {
                    Util.operationSwitch(operation, record);
                }

                if (scope.onOperation) {
                    scope.onOperation(operation);
                }
            }
        };

        var cellsrenderer = function (row, column, value, rowData) {
            if(Config.operationType == 'icon'){
                return '<!-- ko foreach:_operations -->' +
                    '<span class="mr-1" data-bind="css:css,click:function(){$parent._onOperation($data,' + rowData.id + ')},attr:{title:title}"></span>' +
                    '<!-- /ko -->';
            }
            else{
                return '<div class="dropdown">' +
                    '<button class="btn  dropdown-toggle pl-1 pr-1 pt-0 pb-0" type="button"  data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">操作</button>' +
                    '<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">'+
                    '<!-- ko foreach:_operations -->' +
                    '<span class="dropdown-item" data-bind="text:title,click:function(){$parent._onOperation($data,' + rowData.id + ')}"></span>' +
                    '<!-- /ko --></div></div>';
            }
        };

        scope._store = new Store({
            model:scope.store.model,
            id:scope.store.id,
            pageSize:0,
            autoLoad:false,
            onInitComplete: function () {
                var source =
                    {
                        dataType: "array",
                        dataFields: scope._store.getModelFields(),
                        hierarchy:
                            {
                                keyDataField: {name: scope.keyDataField},
                                parentDataField: {name: scope.parentDataField}
                            },
                        id: scope.keyDataField,
                        localData: []
                    };
                var dataAdapter = new $.jqx.dataAdapter(source);

                var columns = [];

                scope.displayFields.forEach(function (fieldName) {
                    var field = scope._store.getModelField(fieldName);
                    var tempField = {text: field.alias, dataField: field.name};

                    if(field.width){
                        tempField.width = field.width;
                    }

                    columns.push(tempField);
                });

                if (scope.operations && scope.operations.length > 0) {
                    columns.push({text: '操作',width:120,align:'center',cellsAlign:'center', cellsrenderer: cellsrenderer});
                }

                //add the tree grid init method in a async function because id is ko bind
                require([], function () {
                    $(scope._jqId).jqxTreeGrid(
                        {
                            columnsHeight: 48,
                            width: '99.8%',
                            source: dataAdapter,
                            theme: "bootstrap",
                            rendered: function () {
                                ko.cleanNode($("#table" + scope._id)[0]);
                                ko.applyBindings(scope, $("#table" + scope._id)[0]);
                            },
                            columns: columns
                        });
                    $(scope._jqId).on('rowSelect',
                        function (event) {
                            var row = event.args.row;

                            if (row[scope.keyDataField] instanceof Number) {
                                row[scope.keyDataField] = row[scope.keyDataField].toString();
                            }

                            if (row[scope.parentDataField] instanceof Number) {
                                row[scope.parentDataField] = row[scope.parentDataField].toString();
                            }

                            if (scope._selectedId == event.args.row[scope.keyDataField]) {
                                $(scope._jqId).jqxTreeGrid('unselectRow', scope._selectedId );
                                scope._selectedId = undefined;

                                if(scope.onNoneRowSelect) scope.onNoneRowSelect();
                            }
                            else {
                                if (scope.onRowSelect) scope.onRowSelect(event.args.row);

                                scope._selectedId = event.args.row[scope.keyDataField];
                            }
                        }
                    );

                    scope._store.load();
                });


                scope._store.addLoadListener('complete', function () {
                    source.localdata = ko.mapping.toJS(scope._store.records);
                    dataAdapter.dataBind();
                    //$("#" + scope.id).jqxTreeGrid('expandRow', '1');
                    scope._selectedId = undefined;
                    if (scope.onNoneRowSelect) scope.onNoneRowSelect();
                });
            }
        });
    }

    return ViewModel;
});
